package org.swift.commons.xml;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.llom.factory.OMXMLBuilderFactory;
import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder;
import org.apache.axiom.soap.impl.dom.soap11.SOAP11Factory;
import org.apache.axiom.soap.impl.dom.soap12.SOAP12Factory;

public class SOAPUtil {
	public static OMElement getBodyContents(OMElement soapMessage) {
		// TODO: Should get the declared namespaces of the soap message element,
		// get the QName of the root element, look up its namespaceURI and then
		// choose the right factory based on the namespace URI... a later time..
		OMElement body = null;
		try {
			SOAP11Factory f = new SOAP11Factory();
			StAXSOAPModelBuilder builder = OMXMLBuilderFactory
					.createStAXSOAPModelBuilder(f, soapMessage
							.getXMLStreamReader());
			body = builder.getSOAPEnvelope().getBody();	
		} catch (Exception exc) {
			try {
				SOAP12Factory f = new SOAP12Factory();
				StAXSOAPModelBuilder builder = OMXMLBuilderFactory
						.createStAXSOAPModelBuilder(f, soapMessage
								.getXMLStreamReader());
				body = builder.getSOAPEnvelope().getBody();
			} catch (Exception e) {
				return soapMessage;
			}
		}
		if (body != null && body.getChildElements().hasNext()){
			return body.getFirstElement();
		} else {
			return body;
		}
	}
}
